
<!DOCTYPE html>
<!--[if IEMobile 7 ]><html class="no-js iem7"><![endif]-->
<!--[if lt IE 9]><html class="no-js lte-ie8"><![endif]-->
<!--[if (gt IE 8)|(gt IEMobile 7)|!(IEMobile)|!(IE)]><!--><html class="no-js"><!--<![endif]-->
<head>
  <meta charset="utf-8">
  <title>
    
  HTML5 dataset 属性不为人知的地方（命名规则和原理） - beace lee的博客
  

  </title>
  <meta name="author" content="">
  <meta name="description" content="周日被我射熄火了，现在是周一">

  <meta name="HandheldFriendly" content="True">
  <meta name="MobileOptimized" content="320">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  
  <link href="asset/css/screen.css" media="screen, projection" rel="stylesheet" type="text/css">  
  <link href="atom.xml" rel="alternate" title="beace lee的博客" type="application/atom+xml">
  <script src="asset/js/modernizr-2.0.js"></script>
  <script src="asset/js/jquery.min.js"></script>
  <script src="asset/highlightjs/highlight.pack.js"></script>
  <link href="asset/highlightjs/styles/monokai_sublime.css" media="screen, projection" rel="stylesheet" type="text/css">
  <script>hljs.initHighlightingOnLoad();</script>

  <style type="text/css">
  .cat-children-p{ padding: 6px 0px;}
  .hljs{background: none;}
  </style>
  <script type="text/javascript">
  var isAddSildbar = true;
  </script>
  <script src="asset/js/octopress.js" type="text/javascript"></script>
</head>
<script type="text/javascript">
//链接新开窗口
function addBlankTargetForLinks () {
  $('a[href^="http"]').each(function(){
      $(this).attr('target', '_blank');
  });
}
$(document).ready(function(event) {
  addBlankTargetForLinks();
});
</script>
<body   >
  <header role="banner"><hgroup>
  <a href="index.html" class="beace-img">
    <img src="https://images-manager.oss-cn-shanghai.aliyuncs.com/self/logo.jpg" />
  </a>
  <div class="header-title">
    <h1><a href="index.html">beace lee的博客</a></h1>
    <h2>周日被我射熄火了，现在是周一
  </div>
    
</hgroup>

</header>
  <nav role="navigation"><ul class="subscription" data-subscription="rss">
  <li><a href="atom.xml" rel="subscribe-rss" title="subscribe via RSS">RSS</a></li>
  
</ul>
  
<!-- <form action="https://google.com/search" method="get">
  <fieldset role="search">
    <input type="hidden" name="q" value="site:beace.github.io" />
    <input class="search" type="text" name="q" results="0" placeholder="Search"/>
  </fieldset>
</form> -->
<a class="beace-github" href="https://github.com/BeAce"></a>
  
<ul class="main-navigation">

  <li id=""><a target="_self" href="index.html">Home</a></li>

  <li id=""><a target="_self" href="archives.html">Archives</a></li>

  <li id=""><a target="_self" href="about.html">About</a></li>

</ul>

</nav>
  <div id="main">
    <div id="content"> 
<div>
	<article class="hentry" role="article">
	<header>
			  	<h1 class="entry-title">HTML5 dataset 属性不为人知的地方（命名规则和原理）</h1>
				<p class="meta"><time datetime="2017-04-18T14:06:51+08:00" pubdate data-updated="true">2017/4/18 14:6 下午</time></p>
			 </header>
		  	<div class="entry-content">
			  	<p><em>HTML5</em>在元素中增加了<em>data-*</em>，可以允许用户自定义属性。这种可读写的方式极大的方便了<br/>
操作元素时的数据存储、状态保留。经常可以在各大主流网站上面看到它的使用，例如淘宝首页。</p>

<p><img src="media/14924956119427/14924960637439.jpg" alt=""/></p>

<span id="more"></span><!-- more -->

<p>下面记录下一些使用细节。</p>

<h2 id="toc_0">语法</h2>

<p>在语法上，我们可以在任何DOM元素上添加该属性，但是需要遵照一些命名规则。</p>

<h3 id="toc_1">命名规则</h3>

<ul>
<li>必须使用<em>data-</em>最为前缀，<em>data-</em>后面数据类型允许<em>字符串</em>，<em>数字</em>，<em>-</em>，<em>.</em>，<em>:</em>，<em>_</em> 。当然了，在使用JavaScript获取时就不能单纯地将一些特殊字符直接点属性使用了。</li>
</ul>

<p><img src="media/14924956119427/14924965473433.jpg" alt=""/></p>

<ul>
<li>不可以使用大写字母。这里说不可以是不太准确的，建议可能更加恰当。但是为了避免出错还是不要使用这种写法，尤其是驼峰式命名。因为获取<em>dataset</em>时，会看到输出的object中该属性都变为了小写。</li>
</ul>

<h4 id="toc_2">举个例子</h4>

<p>下面这段代码中加入了自定义属性<em>data-bgColor</em>，采用了驼峰式命名，希望能够记住该属性通过JavaScript动态赋值。</p>

<pre><code class="language-html">&lt;div id=&quot;container2&quot; data-bgColor=&quot;yellow&quot;&gt;&lt;/div&gt;
</code></pre>

<p>可是通过JavaScript获取到该属性时，却变为了小写。如下图。</p>

<pre><code class="language-javascript">var container2 = document.getElementById(&#39;container2&#39;);
var dataset2 = container2.dataset;
console.log(dataset2);
</code></pre>

<p><img src="media/14924956119427/14924968409115.jpg" alt=""/></p>

<p>那如果非要使用驼峰式命名该如何呢？上面有个例子举得好像正好规避了这个问题。有这样的一个属性<em>data-name-1</em>，访问到的还是<em>name-1</em>，如果将其换为字符串<em>data-bg-color</em>，可以看到获取的时候就变为了驼峰。</p>

<p><img src="media/14924956119427/14924973616744.jpg" alt=""/></p>

<p>这是因为浏览器有一个<em>Name conversion（命名转换）</em>的过程，在获取时将<em>data-</em>去掉，并且将之后的命名中如果含有破折号的，将其变为大写。当然了，变为大写的字符也是有范围的。首先它必须具有大写，<em>ASCII</em>中的<em>A</em>到<em>Z</em>。</p>

<blockquote>
<p>any dash (U+002D) followed by an ASCII lowercase letter a to z, the dash is removed and the letter is transformed into its uppercase counterpart;</p>
</blockquote>

<p>当然了，这是一个双向的过程。我们也可以给DOM元素指定不存在的<em>data-</em>属性。</p>

<pre><code class="language-javascript">container2.dataset.itemIndex = &quot;1&quot;;
</code></pre>

<p>这时，在<em>HTML</em>中，将会如此渲染。如下图，可以看到又加上了破折号<em>data-item-index</em>。</p>

<p><img src="media/14924956119427/14924980360328.jpg" alt=""/></p>

<blockquote>
<p>any ASCII uppercase letter A to Z is transformed into a dash followed by its lowercase counterpart;</p>
</blockquote>

<h2 id="toc_3">操作</h2>

<p><code>JavaScript</code>来获取data-*属性。</p>

<h3 id="toc_4">获取并操作元素样式</h3>

<pre><code class="language-javascript">var container = document.getElementById(&#39;container&#39;);
var dataset = container.dataset;
container.style = `
width: ${dataset.width};
height: ${dataset.height};
background-color: ${dataset.bgcolor};`;
</code></pre>

<p><img src="media/14924956119427/14924987600651.jpg" alt=""/></p>

<h3 id="toc_5">也可以在选取特定的元素上起作用。</h3>

<pre><code class="language-javascript">const audio = document.querySelector(`audio[data-key=&quot;${e.keyCode}&quot;]`);
</code></pre>

			</div>

		
	  
		<footer>
		 <p class="meta">

			<strong>Categories:</strong>&nbsp; 
			<span class="categories">
			
			    <a class='category' href='html5.html'>html5</a>&nbsp;
			 
			</span>
		    </p>
		    <p class="meta">
		      
		 </p>
	    
		<div class="sharing">
		  <!-- 多说公共JS代码 start (一个网页只需插入一次) -->
<script type="text/javascript">
var duoshuoQuery = {short_name:"shimin"};
  (function() {
    var ds = document.createElement('script');
    ds.type = 'text/javascript';ds.async = true;
    ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
    ds.charset = 'UTF-8';
    (document.getElementsByTagName('head')[0] 
     || document.getElementsByTagName('body')[0]).appendChild(ds);
  })();
  </script>
<!-- 多说公共JS代码 end -->
          

          
              <div class="ds-thread" data-thread-key="HTML5%20dataset.html" data-url="beace.github.io/HTML5%20dataset.html" data-title="HTML5 dataset 属性不为人知的地方（命名规则和原理）"></div>
          

		</div>

	    <p class="meta">
	    
	    
	        <a class="basic-alignment right" href="14921760383479.html" 
	        title="Next Post: 【摘抄】You Don't Need jQuery (选自 https://travis-ci.org/oneuijs/You-Dont-Need-jQuery)">【摘抄】You Don't Need jQuery (选自 https://travis-ci.org/oneuijs/You-Dont-Need-jQuery) &raquo;</a>
	    
	    </p>
	  </footer>
	</article>
</div>
 <aside class="sidebar"> 

	<section>
	  <h1>Categories</h1>
	  <ul id="recent_posts">
	  
	      <li class="post">
	        <a href="doc-css.html"><strong>doc-css&nbsp;(5)</strong></a>
	        
	        
	        
	      </li>
	  
	      <li class="post">
	        <a href="json-server.html"><strong>json-server&nbsp;(1)</strong></a>
	        
	        
	        
	      </li>
	  
	      <li class="post">
	        <a href="javascript-funny.html"><strong>javascript-funny&nbsp;(2)</strong></a>
	        
	        
	        
	      </li>
	  
	      <li class="post">
	        <a href="star.html"><strong>star&nbsp;(1)</strong></a>
	        
	        
	        
	      </li>
	  
	      <li class="post">
	        <a href="html5.html"><strong>html5&nbsp;(1)</strong></a>
	        
	        
	        
	      </li>
	   
	  </ul>
	</section>
	<section>
	  <h1>Recent Posts</h1>
	  <ul id="recent_posts">
	  
	      
		      <li class="post">
		        <a href="HTML5%20dataset.html">HTML5 dataset 属性不为人知的地方（命名规则和原理）</a>
		      </li>
	     
	  
	      
		      <li class="post">
		        <a href="14921760383479.html">【摘抄】You Don't Need jQuery (选自 https://travis-ci.org/oneuijs/You-Dont-Need-jQuery)</a>
		      </li>
	     
	  
	      
		      <li class="post">
		        <a href="JavaScript-arguments.html">JavaScript Arguments</a>
		      </li>
	     
	  
	      
		      <li class="post">
		        <a href="javascript-object-funny.html">JavaScript一些有趣的地方</a>
		      </li>
	     
	  
	      
		      <li class="post">
		        <a href="css-draw-rectangle.html">分享一些CSS画图技巧(1)——矩形</a>
		      </li>
	     
	  
	      
	  
	      
	  
	      
	  
	      
	  
	      
	   
	  </ul>
	</section>
	
</aside> </div></div>
  <footer role="contentinfo"><p>
  Copyright &copy; 2017 -  -
  <span class="credit">Powered by <a target="_blank" href="https://beace.github.io">Beace</a> &nbsp;&nbsp; Theme by <a href="http://octopress.org">Octopress</a></span>
</p>

</footer>
<script src="asset/js/big-picture.min.js"></script>  
<script>
  (function() {
    function setClickHandler(id, fn) {
      document.querySelector(id).onclick = fn;
    }
    setClickHandler('body', function(e) {
      e.target.tagName === 'IMG' && BigPicture({
        el: e.target,
        imgSrc: e.target.src
      });
    });
  })()
</script>

  


<script type="text/javascript">
var duoshuoQuery = {short_name:'shimin'};
  (function() {
    var ds = document.createElement('script');
    ds.type = 'text/javascript';ds.async = true;
    ds.src = (document.location.protocol == 'https:' ? 'https:' : 'http:') + '//static.duoshuo.com/embed.js';
    ds.charset = 'UTF-8';
    (document.getElementsByTagName('head')[0] 
     || document.getElementsByTagName('body')[0]).appendChild(ds);
  })();
  </script>
    



<script>
  (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
  })(window,document,'script','https://www.google-analytics.com/analytics.js','ga');

  ga('create', 'UA-83986231-2', 'auto');
  ga('send', 'pageview');

</script>
</body>
</html>